import md5 from './md5.js';

const app = getApp();
let rootDocment = app.globalData.rootUrl +'/Admin/';
// let rootDocment = app.globalData.rootUrl +'/Administor/';
// let rootDocment ='http://cdj_test.caidj.net/Admin/';
// let rootDocment = '/apis/Admin/';
 
// ↓↓↓加密请求一条龙
var header = '';

// 方法名、路径、参数（没有参数传{}），回调、是否不需要token也可请求
function $https(method,url,data,callback,notoken){
	let timeStamp = Math.round(new Date().getTime() / 1000);
	// let timeStamp = 1616650425;
	let params = {
		timeStamp,
	};
		// getApp().setTitle()
	var token = uni.getStorageSync("administor_token")
	if (token || notoken) {
		header = {
			'Accept': 'application/json',
			'content-type': 'application/json', //
			'Authorization': uni.getStorageSync("administor_token"),
		}
		let filtData = {};
		//data过滤数组
		for(let i in data){
			if(!Array.isArray(data[i])){
				filtData[i] = data[i];
			}
		}
		let newParams = Object.assign(filtData,params);	//加入时间戳、data
		let sign = md5.hexMD5(objKeySort(newParams) + app.globalData.appsecret);	//转换成sign
		let datas = Object.assign(data, Object.assign({'sign':sign},params))		//时间戳、data、sign
		switch(method){
			case 'GET':{getRequest(url,datas,callback);break;};
			case 'GETN':{getRequests(url,datas,callback);break;};	//不带加载
			case 'POST':{postRequest(url,datas,callback);break;};
			case 'POSTN':{postRequests(url,datas,callback);break;};		//不带加载
			default:{getRequest(url,datas,callback);}
		}
	}else{
		uni.redirectTo({
			url: '/pages/account/login'
		});
	}

}
// ↑↑↑

//get请求带加载
function getRequest(url, datas, success) { 
	uni.showLoading({
		title: '加载中...',
		duration: 2000,
		mask: true,
		success: function(res) {
			uni.request({
				url: rootDocment + url,
				method: 'GET',
				header:header,
				data: datas,
				success: res => {
					// #ifndef MP-WEIXIN
					if (res.header.authorization != undefined) {
						uni.setStorageSync("administor_token", res.header.authorization);
					}
					// #endif
					if (res.header.Authorization != undefined) {
						uni.setStorageSync("administor_token", res.header.Authorization);
					}
					if (res.data.code == 400) {
						uni.showToast({
							title: res.data.msg,
							icon: 'none',
							duration: 1000,
							success: function() {

							}
						})
					}
					if (res.data.errcode == 50020) {
						uni.removeStorageSync('administor_token');
						uni.navigateTo({
							url: '/pages/account/login'
						});
						
					}
					if (res.data.code == 404) {

						uni.navigateTo({
							url: '/pages/account/404'
						});
					}
					uni.hideLoading();
					success(res);
				},
				fail: res => {
					uni.hideLoading()
					uni.showToast({
						title: '网络错误',
						icon:'none'
					})
				},

			})
		},
		fail: function(res) {},
		complete: function(res) {},
	})


}

//get请求
function getRequests(url, datas, success) {
	uni.request({
		url: rootDocment + url,
		method: 'GET',
		header,
		data: datas,
		success: res => {
			
			// #ifndef MP-WEIXIN
			if (res.header.authorization != undefined) {
				uni.setStorageSync("administor_token", res.header.authorization);
			}
			// #endif
			if (res.header.Authorization != undefined) {
				uni.setStorageSync("administor_token", res.header.Authorization);
			}
			if (res.data.errcode == 50020) {
				uni.removeStorageSync('administor_token');
				uni.navigateTo({
					url: '/pages/account/login'
				});
			}
			if (res.data.code == 404) {
				uni.navigateTo({
					url: '/pages/account/404'
				});
			}
			if (res.data.code == 408) {
				uni.navigateTo({
					url: '/pages/account/service'
				})
			}
			success(res)
		},
		fail: res => {
			uni.showToast({
				title: '网络错误',
				icon:'none'
			})
		},

	})

}

//POST请求带加载中
function postRequest(url, datas, success) {
	uni.showLoading({
		title: '加载中',
		mask: true,
		success: function(res) {
			uni.request({
				url: rootDocment + url,
				method: 'POST',
				header,
				data: datas,
				success: res => {
					// #ifndef MP-WEIXIN
					if (res.header.authorization != undefined) {
						uni.setStorageSync("administor_token", res.header.authorization);
					}
					// #endif
					if (res.header.Authorization != undefined) {
						uni.setStorageSync("administor_token", res.header.Authorization);
					}
					if (res.data.code == 400) {
						uni.showToast({
							title: res.data.msg,
							icon: 'none',
							duration: 1000,
							success: function() {

							}
						})
					}
					if (res.data.errcode == 50020) {
						uni.removeStorageSync('administor_token');
						uni.navigateTo({
							url: '/pages/account/login'
						});

					}
					if (res.data.code == 403) {
						uni.showToast({
							title: '账号已禁用',
							icon: 'none',
							duration: 1000,
							success: function() {
								uni.navigateTo({
									url: '/pages/account/login'
								});
							}
						})
					}
					if (res.data.code == 404) {

						uni.navigateTo({
							url: '/pages/account/404'
						});

					}
					if (res.data.code == 408) {
						uni.showToast({
							title: '抱歉，您的服务已到期，请联系《菜东家》工作人员续费！',
							icon: 'none',
							duration: 2000,
						})
					}
					uni.hideLoading();
					success(res);
				},
				fail: res => {
					uni.hideLoading()
					uni.showToast({
						title: '网络错误',
						icon:'none'
					})
				},
				complete(){
				}

			})
		},
		fail: function(res) {},
		complete: function(res) {},
	})

}
//POST请求不带加载中
function postRequests(url, datas, success) {
	uni.request({
		url: rootDocment + url,
		method: 'POST',
		header,
		data: datas,
		success: res => {
			// #ifndef MP-WEIXIN
			if (res.header.authorization != undefined) {
				uni.setStorageSync("administor_token", res.header.authorization);
			}
			// #endif
			if (res.header.Authorization != undefined) {
				uni.setStorageSync("administor_token", res.header.Authorization);
			}
			if (res.data.errcode == 50020) {
				uni.removeStorageSync('administor_token');
				uni.navigateTo({
					url: '/pages/account/login'
				});

			}
			success(res);
		},
		fail: res => {
			uni.showToast({
				title: '网络错误',
				icon:'none'
			})
		},

	})
}
function objKeySort(obj) { //排序的函数
	var newkey = Object.keys(obj).sort();
	//先用Object内置类的keys方法获取要排序对象的属性名，再利用Array原型上的sort方法对获取的属性名进行排序，newkey是一个数组
	var newObj = {}; //创建一个新的对象，用于存放排好序的键值对
	var sz = '';
	for (var i = 0; i < newkey.length; i++) { //遍历newkey数组
		newObj[newkey[i]] = obj[newkey[i]]; //向新创建的对象中按照排好的顺序依次增加键值对
	}
	Object.keys(newObj).forEach(function(key) {
		sz += '&' + key + '=' + newObj[key]
	});
	return sz.substr(1); //返回排好序的新对象
}



module.exports = {
	$https
}